package DB;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;


public class ConnectionPool {
	private static ConnectionPool connectionPool = null;
	private static Vector<Connection> freeConnections;
	private static String url = "localhost/Webshop";
	private static String user = "root";
	private static String password = "hajfot59";	
	
	/**
	 * Creates a number of connections for use.
	 */
	private ConnectionPool(){
		freeConnections = new Vector<Connection>();
		try {
			for(int i = 0; i < 5; i++){
				Class.forName("com.mysql.jdbc.Driver").newInstance();
				freeConnections.add(DriverManager.getConnection("jdbc:mysql://" + url, user, password));
			}
		} catch (SQLException e){
			
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Get a connection from the pool, if all connections are busy a new connection is maid.
	 * @return - A connection to the database.
	 */
	public synchronized static Connection getConnection(){
		if(connectionPool == null)
			connectionPool = new ConnectionPool();
		if(freeConnections.isEmpty()){
			System.out.println("ConnectionPool is empty");
			try {
				Class.forName("com.mysql.jdbc.Driver").newInstance();
				return DriverManager.getConnection("jdbc:mysql://" + url, user, password);
			} catch (SQLException e) {
			} catch (InstantiationException e) {
			} catch (IllegalAccessException e) {
			} catch (ClassNotFoundException e) {
			}
			return null;
		}
		Connection connection = freeConnections.firstElement();
		freeConnections.remove(0);
		return connection;
	}
	
	/**
	 * Return a connection to the Connection Pool.
	 * @param connection - The connection to be returned.
	 */
	public synchronized static void releaseConnection(Connection connection){
		freeConnections.add(connection);
	}

}
